import axios from 'axios'
// import store from '../store'
import {
  CONSTANT
} from "@/utils/constant"
import {
  tools,
  wxLogin
} from "@/utils/tools"
import {
  Toast
} from 'vant'
import store from "@/store"
import router from '@/router'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 50000, // 请求超时时间
  method: 'post',
  withCredentials: true,
  post: {
    'Content-Type': 'application/json'
  },
})
// request拦截器
let toastLoading
service.interceptors.request.use(config => {
  if (!config.noLoading) {
    //不需要显示加载弹框
    toastLoading = Toast.loading({
      mask: true,
      message: '加载中...',
      duration: 0,
      // mask: false
    })
  }
  let password = ''
  if (config.noEncrypt) {
    //不需要加密的接口
    password = CONSTANT.password
  } else {
    //需要token加密
    password = store.state.loginInfo.secretKey
  }
  //参数
  let obj = {
    token: store.state.loginInfo.token,
    userId: store.state.loginInfo.userId,
    source: 4,
    ip: returnCitySN.cip,
    content: '',
  }
  let header = {
    userId: store.state.loginInfo.userId,
    ip: returnCitySN.cip,
    source: 4
  }
  obj.content = config.data
  obj.content.header = header
  //content 用私钥加密
  //整体用公钥加密
  obj.content = tools.encrypt(JSON.stringify(obj.content), password)
  let parameters = tools.encrypt(JSON.stringify(obj), CONSTANT.password)
  config.data = parameters
  return config
}, error => {
  // Do something with request error
  //关闭加载中提示
  if (toastLoading) {
    toastLoading.clear()
  }
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    //关闭加载中提示
    if (toastLoading) {
      toastLoading.clear()
    }
    let data = tools.newLine(response.data)
    let res = tools.decrypt(data, "hxsports")
    res = JSON.parse(res)
    console.error(res);

    const code = res.errCode
    const msg = res.errMsg
    if (code !== '0000') {
      Toast(msg)
      if (code === '6888' || code === '6883') {
        router.push('/login')
        // wxLogin()
      }
      return Promise.reject(res)
    } else {
      if (toastLoading) {
        toastLoading.clear()
      }
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Toast(error.errMsg)
    return Promise.reject(error)
  }
)

export default service
